package com.huan.project;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

    public class TestGetP {
        public static void main(String[] args) {
            try {
                // 设置请求 URL
                URL url = new URL("https://tenapi.cn/v2/acg");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                // 设置请求方法为 POST
                connection.setRequestMethod("POST");

                // 启用输入输出流
                connection.setDoOutput(true);

                // 设置请求参数
                String parameters = "format=json";
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = parameters.getBytes("utf-8");
                    os.write(input, 0, input.length);
                }
                JSONObject jsonObj = null;
                // 获取响应
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line;
                    StringBuilder response = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    System.out.println("Response: " + response.toString());
                    jsonObj = new JSONObject(response.toString());
                }
                //处理json数据，取到图片url
                String data = jsonObj.get("data").toString();
                int start = data.indexOf("http");
                int end = data.indexOf(".jpg")+4;
                String purl = data.substring(start,end);
                System.out.println(purl);
                // 关闭连接
                connection.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

